package com.yida.wy.basic.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.mybatisflex.core.query.QueryWrapper;
import com.yida.common.core.exception.ServiceException;
import com.yida.common.core.utils.DateUtils;
import com.yida.common.core.utils.StringUtils;
import com.yida.common.security.utils.SecurityUtils;
import com.yida.wy.basic.domain.WyOwnerAttest;
import com.yida.wy.basic.domain.dto.WyOwnerAttestDetailDTO;
import com.yida.wy.basic.domain.request.WyOwnerAttestApproveRequest;
import com.yida.wy.basic.domain.request.WyOwnerAttestSubmitRequest;
import com.yida.wy.basic.enums.WyOwnerAttestApproveStatus;
import com.yida.wy.basic.mapper.WyOwnerAttestMapper;
import com.yida.wy.basic.service.IWyOwnerAttestService;
import com.yida.wy.common.constant.WyConstants;
import com.yida.wy.common.domain.WyBaseHouse;
import com.yida.wy.common.domain.WyBaseOwner;
import com.yida.wy.common.service.IWyBaseHouseService;
import com.yida.wy.common.service.IWyBaseOwnerService;
import com.yida.wy.common.service.impl.BasicServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

import static com.yida.wy.common.domain.table.WyBaseOwnerTableDef.WY_BASE_OWNER;

/**
 * 业主信息认证Service业务层处理
 *
 * @author lqq
 * @date 2023-08-26
 */
@Service
public class WyOwnerAttestServiceImpl extends BasicServiceImpl<WyOwnerAttestMapper, WyOwnerAttest> implements IWyOwnerAttestService {

    @Resource
    private WyOwnerAttestMapper ownerAttestMapper;

    @Resource
    private IWyBaseOwnerService ownerService;

    @Resource
    private IWyBaseHouseService houseService;

    /**
     * 提交认证资料
     *
     * @param request 业主信息认证
     * @return 结果
     */
    @Override
    public int submit(WyOwnerAttestSubmitRequest request) {
        WyOwnerAttest gwjOwnerAttest = BeanUtil.copyProperties(request, WyOwnerAttest.class);
        gwjOwnerAttest.setApplicantTime(DateUtils.getNowDate());
        gwjOwnerAttest.setStatus(WyOwnerAttestApproveStatus.NOT_APPROVE.getCode());
        gwjOwnerAttest.setCreateBy(request.getOwnerName());
        // 查询旧数据
        WyBaseHouse baseHouse = houseService.getById(request.getHouseId());
        WyOwnerAttestDetailDTO oldOwnerInfo = new WyOwnerAttestDetailDTO() {
            {
                setBuildName(request.getBuildName());
                setCommunityName(request.getCommunityName());
                setRoomNum(request.getRoomNum());
                setCertificateNum(baseHouse.getCertificateNum());
                setHouseLocation(baseHouse.getHouseLocation());
            }
        };
        WyBaseOwner baseOwner = ownerService.getOne(QueryWrapper.create().where(WY_BASE_OWNER.HOUSE_CODE.eq(request.getHouseCode()).and(WY_BASE_OWNER.AREA_ID.eq(request.getAreaId()))));
        if (StringUtils.isNotNull(baseOwner)) {
            oldOwnerInfo.setOwnerName(baseOwner.getOwnerName());
            oldOwnerInfo.setOwnerPhone(baseOwner.getOwnerPhone());
            oldOwnerInfo.setCardNum(baseOwner.getCardNum());
        }
        gwjOwnerAttest.setOldOwnerInfo(JSONUtil.toJsonStr(JSONUtil.parseObj(oldOwnerInfo, false)));
        gwjOwnerAttest.setHouseLocation(baseHouse.getHouseLocation());
        return ownerAttestMapper.insert(gwjOwnerAttest);
    }

    /**
     * 审批通过
     *
     * @param request /
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void approve(WyOwnerAttestApproveRequest request) {
        WyOwnerAttest gwjOwnerAttest = ownerAttestMapper.selectOneById(request.getOwnerAttestId());
        if (StringUtils.isNull(gwjOwnerAttest)) {
            throw new ServiceException("审批失败,查无业主认证申请资料");
        }
        if (!StringUtils.equals(gwjOwnerAttest.getStatus(), WyOwnerAttestApproveStatus.NOT_APPROVE.getCode())) {
            throw new ServiceException("审批失败,无法重复审核");
        }
        String optName;
        Long optId;
        if (request.getOutsideFlag()) {
            optName = SecurityUtils.getLoginUser().getSysOutsideUser().getRealName();
            optId = SecurityUtils.getLoginUser().getSysOutsideUser().getUserId();
        } else {
            optName = SecurityUtils.getLoginUser().getSysUser().getRealName();
            optId = SecurityUtils.getLoginUser().getSysUser().getUserId();
        }
        gwjOwnerAttest.setApproveUserName(optName);
        gwjOwnerAttest.setApproveUserId(optId);
        gwjOwnerAttest.setUpdateBy(optName);
        gwjOwnerAttest.setStatus(request.getApproveCode());
        gwjOwnerAttest.setApproveContent(request.getApproveContent());
        gwjOwnerAttest.setApproveTime(DateUtils.getNowDate());
        if (ownerAttestMapper.update(gwjOwnerAttest) != 1) {
            throw new ServiceException("审批失败,更新业主认证申请资料失败");
        }
        // 审批通过，更新业主数据
        if (StringUtils.equals(request.getApproveCode(), WyOwnerAttestApproveStatus.PASS.getCode())) {
            // 更新或新增业主数据
            WyBaseOwner baseOwner = ownerService.getOne(QueryWrapper.create().where(WY_BASE_OWNER.HOUSE_CODE.eq(gwjOwnerAttest.getHouseCode()).and(WY_BASE_OWNER.AREA_ID.eq(gwjOwnerAttest.getAreaId()))));
            // 新增
            if (StringUtils.isNull(baseOwner)) {
                WyBaseOwner newOwner = new WyBaseOwner() {
                    {
                        setImportFlag(WyConstants.NO);
                        setAreaId(gwjOwnerAttest.getAreaId());
                        setStreetId(gwjOwnerAttest.getStreetId());
                        setHouseCode(gwjOwnerAttest.getHouseCode());
                        setCardNum(gwjOwnerAttest.getCardNum());
                        setOwnerName(gwjOwnerAttest.getOwnerName());
                        setOwnerPhone(gwjOwnerAttest.getOwnerPhone());
                        setCreateBy(optName);
                    }
                };
                if (!ownerService.save(newOwner)) {
                    throw new ServiceException("审批失败,新增基础业主信息失败");
                }
            }
            // 更新
            else {
                baseOwner.setCardNum(gwjOwnerAttest.getCardNum());
                baseOwner.setOwnerName(gwjOwnerAttest.getOwnerName());
                baseOwner.setOwnerPhone(gwjOwnerAttest.getOwnerPhone());
                baseOwner.setUpdateBy(optName);
                if (!ownerService.updateById(baseOwner)) {
                    throw new ServiceException("审批失败,更新基础业主信息失败");
                }
            }
            // 更新基础房屋产权证号
            WyBaseHouse baseHouse = houseService.getById(gwjOwnerAttest.getHouseId());
            baseHouse.setCertificateNum(gwjOwnerAttest.getCertificateNum());
            baseHouse.setUpdateBy(optName);
            if (!houseService.updateById(baseHouse)) {
                throw new ServiceException("审批失败,更新基础房屋信息失败");
            }
        }
    }
}
